<template>
	<!-- 创建订单页 -->
	<view class="create_order">
		<!-- 订餐方式 -->
		<view class="order-mode">
			<u-cell-group :border="false">
				<u-cell title="瑞幸咖啡">
					<template #value>
						<!-- 胶囊开关 -->
						<view class="order-mode-switch" :class="{active:isTakeOut}">
							<!-- 自提 -->
							<view class="order-mode__item order-mode__self" @click="isTakeOut=false">自取</view>
							<!-- 外卖 -->
							<view class="order-mode__item order-mode__takeOut" @click="isTakeOut=true">外卖</view>
							<!-- 蒙版 -->
							<view class="order-mode__mask"></view>
						</view>
					</template>
				</u-cell>
				<!-- 外卖 -->
				<template v-if="isTakeOut">
					<u-cell title="收货地址" :value="address.area_name||'请选择'" :border="false" @click="toSelectAddr"
						is-link></u-cell>
				</template>
				<!-- 自取 -->
				<template v-else>
					<u-cell title="取餐时间" value="立即取餐" :border="false" is-link></u-cell>
					<u-cell title="就餐方式" :border="false">
						<template #value>
							<!-- 单选框组 -->
							<view class="order-mode-radio">
								<u-radio-group v-model="formData.eatMode" placement="row" activeColor="#ff516b">
									<u-radio shape="circle" label="店内就餐" :name="0"
										:customStyle="{marginRight: '20px'}"></u-radio>
									<u-radio shape="circle" label="打包带走" :name="1"></u-radio>
								</u-radio-group>
							</view>
						</template>
					</u-cell>
					<u-cell title="联系方式" :border="false">
						<template #value>
							<!-- 手机号输入框 -->
							<view class="order-mode-phone">
								<u--input placeholder="请输入手机号" v-model="formData.phone" border="none"></u--input>
								<view class="order-mode-phone__button">
									<u-button text="自动填写" @click="autoFillPhone" color="#ff516b"
										:customStyle="phoneBtnStyle" size="mini" shape="circle" plain></u-button>
								</view>
							</view>
						</template>
					</u-cell>
				</template>
			</u-cell-group>
		</view>
		<!-- 商品详情 -->
		<view class="good-desc">
			<u-cell-group :border="false">
				<u-cell title="商品详情" :border="false" titleStyle="fontWeight: 700;"></u-cell>
				<block v-for="good in cartGoods" :key="good.id">
					<!-- 商品列表 -->
					<view class="good-info">
						<!-- 商品图片 -->
						<view class="good-info__image">
							<image :src="good.image" mode="widthFix|aspectFill"></image>
						</view>
						<!-- 商品数量与价格 -->
						<view class="good-info__desc">
							<!-- 商品价格 -->
							<view class="good-info__title">
								<view class="good-info__name">{{good.name}}</view>
								<view class="good-info__price">￥{{good.price}}</view>
							</view>
							<!-- 商品数量 -->
							<view class="good-info__text">
								<view class="good-info__sku">默认</view>
								<view class="good-info__num">×{{good.num}}</view>
							</view>
						</view>
					</view>
				</block>
				<u-cell title="优惠券" is-link>
					<template #value>
						<u-tag text="1张可用" bgColor="#ff516b" borderColor="#ff516b" size="mini"></u-tag>
					</template>
				</u-cell>
				<u-cell :border="false">
					<template #value>
						<!-- 总计 -->
						<view class="order-total">共{{cartNum}}件商品，小计<span class="order-total__num">￥{{cartTotal}}</span>
						</view>
					</template>
				</u-cell>
			</u-cell-group>
		</view>
		<!-- 支付方式 -->
		<view class="payway">
			<u-cell-group :border="false">
				<u-radio-group v-model="formData.payWay" placement="column" activeColor="#ff516b">
					<u-cell title="支付方式" :border="false" titleStyle="fontWeight: 700;"></u-cell>
					<u-cell title="余额" :border="false">
						<template #icon>
							<i class="balance iconfont icon-yue"></i>
						</template>
						<template #value>
							<u-radio :name="0"></u-radio>
						</template>
					</u-cell>
					<u-cell title="微信" :border="false">
						<template #icon>
							<i class="wepay iconfont icon-weixinzhifu"></i>
						</template>
						<template #value>
							<u-radio :name="1"></u-radio>
						</template>
					</u-cell>
				</u-radio-group>
			</u-cell-group>
		</view>
		<!-- 备注 -->
		<view class="order-remark">
			<u-cell title="备注" :border="false">
				<template #value>
					<u--input placeholder="我们将尽力满足您的要求" fontSize="24rpx" border="none"
						v-model="formData.remark"></u--input>
				</template>
			</u-cell>
		</view>

		<!-- 底部提交订单 -->
		<view class="commit">
			<view class="commit-total">总计：<span class="commit-total__num">￥{{cartTotal}}</span></view>
			<view class="commit-button">
				<u-button text="提交订单" color="#fff" :customStyle="commitBtnStyle" @click="commitOrder"></u-button>
			</view>
		</view>

		<!-- 支付二维码弹窗 -->
		<view class="payPopup" v-if="wxPayCode">
			<u-popup :show="showPopup" mode="bottom" round="30" @close="closePopup" closeOnClickOverlay closeable>
				<view class="qrcode">
					<!-- 标题 -->
					<view class="qrcode-title">扫码付款</view>
					<!-- 二维码 -->
					<view class="qrcode-image">
						<uqrcode ref="uqrcode" canvas-id="qrcode" :value="wxPayCode">
						</uqrcode>
					</view>
				</view>
			</u-popup>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				/* 样式 */
				// 自动填写按钮样式
				phoneBtnStyle: {
					borderColor: '#ff516b',
					backgroundColor: '#ffeef1'
				},
				// 提交按钮样式
				commitBtnStyle: {
					backgroundColor: '#ff516b',
					height: '100%',
					border: 'none',
					borderRadius: '0'
				},
				/* 数据 */
				// 自取？外卖？
				isTakeOut: false,
				// 表单信息
				formData: {
					// 取餐时间
					getTimeAt: '',
					// 就餐方式， 0 店内就餐，1 打包带走
					eatMode: 0,
					// 联系方式
					phone: '',
					// 备注
					remark: '',
					// 支付方式， 0 余额支付，1 微信支付
					payWay: 0,
				},
				// 购物车商品
				cartGoods: [],
				// 收货地址
				address: {},
				// 收货地址id
				addrId: null,
				// 微信支付付款链接
				wxPayCode: '',
				// 微信支付弹出层控制
				showPopup: false,
				// 微信支付查询定时器
				payTimer: null,
			}
		},
		computed: {
			// 购物车商品种类数量
			cartNum() {
				return this.cartGoods.length;
			},
			// 购物车商品总价
			cartTotal() {
				return this.cartGoods.reduce((a, b) => a + b.num * b.price, 0).toFixed(2);
			},
		},
		methods: {
			// 自动填充手机号
			autoFillPhone() {
				this.formData.phone = '13412341234';
			},
			// 去选择地址页
			toSelectAddr() {
				// 跳转到地址列表页，并且需要选择功能
				this.$Router.push({
					path: '/address',
					query: {
						needSelect: true
					}
				});
			},
			// 获取购物车商品
			async getCartGoods() {
				let data = await this.$api.cart.getGoodsInCartAPI();
				// 保存购物车商品信息(过滤数据)
				this.cartGoods = data.result.map(g => {
					return {
						id: g.id,
						goods_id: g.s_good.id,
						name: g.s_good.name,
						image: g.s_good.s_goods_photos[0].path,
						num: g.num,
						price: g.s_good.price,
						sale_price: g.s_good.sale_price
					}
				});
			},
			// 根据地址id获取地址
			async getAddressById(id) {
				let data = await this.$api.address.getAddressByIdAPI(id);
				// 保存地址信息
				this.address = data.result;
			},
			// 获取默认收货地址
			async getDefaultAddress() {
				let allAddr = await this.$api.address.getAddressAPI();
				// 如果地址列表为空，直接跳出
				if (!allAddr.result.length) return;
				// 请求默认地址
				let data = await this.$api.address.getDefaultAddressAPI();
				// 保存地址信息
				this.address = data.result;
				this.addrId = this.address.id;
			},
			// 添加订单
			async addOrder(options) {
				let data = await this.$api.order.addOrderAPI(options);
				// console.log(data);
				// 判断支付方式
				// 微信支付
				this.createWePay(data.result.order_id);
			},
			// 创建微信支付
			async createWePay(orderId) {
				let data = await this.$api.pay.createWePayAPI(orderId);
				// console.log(data.result.code_url);
				// 将支付url转换为二维码链接
				this.wxPayCode = data.result.code_url;
				// 弹出支付二维码
				this.showPopup = true;
				// 轮询支付状态
				this.payTimer = setInterval(async () => {
					let payResult = await this.$api.pay.queryWXPayStateAPI(orderId);
					// console.log(payResult);
					if (payResult.result.trade_state === 'SUCCESS') {
						// 支付成功
						uni.showToast({
							title: '支付成功',
							icon: 'success'
						});
						// 清除定时器
						clearInterval(this.payTimer);
					}
				}, 3000);
			},
			// 提交订单
			commitOrder() {
				let option = {
					goods_info: this.cartGoods.map(g => ({
						id: g.goods_id,
						num: g.num
					})),
					addr_id: this.addrId,
					shoppingCartIds: this.cartGoods.map(g => g.id)
				}
				if (this.isTakeOut) {
					// 外卖
					// 发起订单
					this.addOrder(option);

				} else {
					// 自取
				}
			},
			// 关闭支付二维码弹出层
			closePopup() {
				this.showPopup = false;
				// 清除支付状态查询定时器
				clearInterval(this.payTimer);
			},
		},
		onLoad() {
			// 获取购物车商品
			this.getCartGoods();
		},
		onShow() {
			// 获取选择的地址id
			this.addrId = uni.getStorageSync('addrId') || null;
			this.addrId ? this.getAddressById(this.addrId) : this.getDefaultAddress();
			uni.removeStorageSync('addrId');
		},
		onUnload() {
			// 清除支付状态查询定时器
			clearInterval(this.payTimer);
		},
		// 路由守卫
		beforeRouteLeave(to, from, next) {
			// 导航离开该组件的对应路由时调用
			// 可以访问组件实例 `this`
			// 清除支付状态查询定时器
			clearInterval(this.payTimer);
			next();
		},
	}
</script>

<style lang="scss" scoped>
	.create_order {
		@include page-bgc(#f6f6f6);
		padding-top: 20rpx;
		padding-bottom: 200rpx;

		// 订餐方式
		.order-mode {
			@include whiteCard();

			// 胶囊开关
			.order-mode-switch {
				position: relative;
				width: 200rpx;
				height: 60rpx;
				font-size: 26rpx;
				border-radius: 30rpx;
				background-color: #f2f2f2;
				display: flex;
				align-items: center;
				justify-content: space-between;
				text-align: center;

				&.active {

					// 自提
					.order-mode__item.order-mode__self {
						color: #000;
					}

					// 外卖
					.order-mode__item.order-mode__takeOut {
						color: #e1e1e1;
					}

					.order-mode__mask {
						left: 50%;
					}
				}

				// 自提/外卖
				.order-mode__item {
					position: relative;
					z-index: 9;
					width: 50%;
					line-height: 60rpx;
					transition: all 0.4s;

					// 自提
					&.order-mode__self {
						color: #e1e1e1;
					}

					// 外卖
					&.order-mode__takeOut {
						color: #000;
					}
				}

				// 蒙版
				.order-mode__mask {
					position: absolute;
					top: 0;
					left: 0;
					width: 50%;
					height: 100%;
					border-radius: 30rpx;
					background-color: #ff516b;
					transition: all 0.4s;
				}
			}

			// 就餐方式单选框
			.order-mode-radio {
				flex: 2;

				// 单选框组样式
				::v-deep .u-radio-group {
					justify-content: flex-end;
				}
			}

			// 手机号输入框
			.order-mode-phone {
				flex: 2;
				display: flex;
				align-items: center;
				justify-content: space-between;

				// 自动填写按钮
				.order-mode-phone__button {
					width: 160rpx;
					margin-left: 10px;
				}
			}
		}

		// 商品详情
		.good-desc {
			@include whiteCard();
			padding: 0 16rpx;

			// 商品列表
			.good-info {
				padding: 10px 15px;
				display: flex;
				align-items: center;

				// 商品图片
				.good-info__image {
					flex-shrink: 0;
					width: 100rpx;
					height: 100rpx;
					overflow: hidden;

					image {
						width: 100%;
						height: 100%;
					}
				}

				// 商品数量与价格
				.good-info__desc {
					flex: 1;
					padding: 4px 0;
					padding-left: 8px;
					display: flex;
					flex-direction: column;
					justify-content: space-between;

					.good-info__title {
						display: flex;
						align-items: center;
						justify-content: space-between;

						.good-info__name,
						.good-info__price {
							font-size: 28rpx;
							color: #000;
						}
					}

					.good-info__text {
						margin-top: 6px;
						display: flex;
						align-items: center;
						justify-content: space-between;

						.good-info__sku,
						.good-info__num {
							font-size: 24rpx;
							color: #999;
						}
					}
				}

			}

			// 总计
			.order-total {
				font-size: 24rpx;
				color: #999;

				.order-total__num {
					font-size: 30rpx;
					color: #000;
				}
			}
		}

		// 支付方式
		.payway {
			@include whiteCard();

			.iconfont {
				font-size: 22px;

				&.balance {
					color: #fe9c01;
				}

				&.wepay {
					color: #09bb07;
				}
			}
		}

		// 备注
		.order-remark {
			@include whiteCard();

			::v-deep .u-input {
				flex: 5;
			}
		}


		// 底部提交订单
		.commit {
			position: fixed;
			left: 0;
			bottom: 0;
			z-index: 999;
			width: 100%;
			height: 110rpx;
			background-color: #f2f2f2;
			display: flex;
			align-items: center;

			.commit-total {
				flex: 1;
				padding-left: 20rpx;
				font-size: 28rpx;
				color: #000;

				.commit-total__num {
					font-size: 36rpx;
					color: $theme-color;
				}
			}

			.commit-button {
				height: 100%;
				width: 200rpx;
			}
		}

		// 支付二维码弹窗
		.payPopup {
			.qrcode {
				.qrcode-title {
					height: 60px;
					text-align: center;
					line-height: 60px;
					font-size: 16px;
					color: #555;
					font-weight: 700;
					border-bottom: 2px solid #ddd;
				}

				.qrcode-image {
					width: 100%;
					height: 320px;
					display: flex;
					align-items: center;
					justify-content: center;
				}
			}
		}
	}
</style>